import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Input,
  Select,
  Modal,
  Form,
  message,
  Popconfirm,
  Tag,
  Tooltip,
  Badge,
  Drawer,
  Descriptions,
  Tabs,
  Upload,
  Image,
  Typography,
  Row,
  Col,
  Statistic,
  Progress,
  Rate,
  InputNumber,
  Switch,
  DatePicker,
  List
} from 'antd';
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  UploadOutlined,
  DownloadOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  FilterOutlined,
  ExportOutlined,
  StarOutlined,
  DollarOutlined,
  TrophyOutlined,
  RiseOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TableProps } from 'antd';
import type { UploadProps } from 'antd';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;
// const { TabPane } = Tabs;

interface Product {
  id: string;
  name: string;
  code: string;
  category: 'stock' | 'bond' | 'mixed' | 'money_market' | 'alternative';
  type: 'fund' | 'insurance' | 'trust' | 'wealth_management';
  status: 'draft' | 'pending' | 'approved' | 'rejected' | 'online' | 'offline';
  riskLevel: 1 | 2 | 3 | 4 | 5;
  minInvestment: number;
  maxInvestment?: number;
  expectedReturn: number;
  actualReturn?: number;
  managementFee: number;
  custodyFee: number;
  subscriptionFee: number;
  redemptionFee: number;
  lockPeriod: number; // 锁定期（天）
  description: string;
  features: string[];
  manager: string;
  company: string;
  establishDate: string;
  netValue: number;
  totalAssets: number;
  subscribers: number;
  rating: number;
  documents: Array<{
    name: string;
    url: string;
    type: 'prospectus' | 'report' | 'contract' | 'other';
  }>;
  images: string[];
  createdAt: string;
  updatedAt: string;
  createdBy: string;
}

interface ProductStats {
  total: number;
  online: number;
  pending: number;
  totalAssets: number;
  avgReturn: number;
}

const ProductManagement: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [categoryFilter, setCategoryFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [riskFilter, setRiskFilter] = useState<string>('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [stats, setStats] = useState<ProductStats>({
    total: 0,
    online: 0,
    pending: 0,
    totalAssets: 0,
    avgReturn: 0
  });
  
  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState<'create' | 'edit'>('create');
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [form] = Form.useForm();
  
  // 产品详情抽屉
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);

  // 加载产品数据
  useEffect(() => {
    loadProducts();
    loadStats();
  }, [pagination.current, pagination.pageSize, searchText, categoryFilter, statusFilter, riskFilter]);

  const loadProducts = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockProducts: Product[] = [
        {
          id: '1',
          name: '稳健增长基金',
          code: 'WM001',
          category: 'mixed',
          type: 'fund',
          status: 'online',
          riskLevel: 3,
          minInvestment: 10000,
          maxInvestment: 1000000,
          expectedReturn: 8.5,
          actualReturn: 9.2,
          managementFee: 1.5,
          custodyFee: 0.25,
          subscriptionFee: 1.0,
          redemptionFee: 0.5,
          lockPeriod: 90,
          description: '专注于稳健增长的混合型基金，适合风险偏好中等的投资者',
          features: ['专业管理', '风险分散', '流动性好'],
          manager: '张基金',
          company: '华夏基金',
          establishDate: '2023-01-15',
          netValue: 1.245,
          totalAssets: 500000000,
          subscribers: 1250,
          rating: 4.5,
          documents: [
            { name: '产品说明书', url: '/docs/prospectus.pdf', type: 'prospectus' },
            { name: '季度报告', url: '/docs/report.pdf', type: 'report' }
          ],
          images: ['/images/product1.jpg'],
          createdAt: '2023-01-10',
          updatedAt: '2024-01-15',
          createdBy: 'admin'
        },
        {
          id: '2',
          name: '保本理财产品',
          code: 'WM002',
          category: 'money_market',
          type: 'wealth_management',
          status: 'pending',
          riskLevel: 1,
          minInvestment: 50000,
          expectedReturn: 4.2,
          managementFee: 0.8,
          custodyFee: 0.1,
          subscriptionFee: 0,
          redemptionFee: 0,
          lockPeriod: 365,
          description: '保本保息的理财产品，适合保守型投资者',
          features: ['保本保息', '固定收益', '银行托管'],
          manager: '李理财',
          company: '招商银行',
          establishDate: '2024-01-01',
          netValue: 1.000,
          totalAssets: 200000000,
          subscribers: 800,
          rating: 4.0,
          documents: [],
          images: [],
          createdAt: '2023-12-20',
          updatedAt: '2024-01-10',
          createdBy: 'admin'
        },
        {
          id: '3',
          name: '高收益股票基金',
          code: 'WM003',
          category: 'stock',
          type: 'fund',
          status: 'online',
          riskLevel: 5,
          minInvestment: 1000,
          expectedReturn: 15.0,
          actualReturn: 18.5,
          managementFee: 2.0,
          custodyFee: 0.3,
          subscriptionFee: 1.5,
          redemptionFee: 1.0,
          lockPeriod: 0,
          description: '专注于高成长股票投资的基金，适合激进型投资者',
          features: ['高收益潜力', '专业选股', '灵活申赎'],
          manager: '王股神',
          company: '易方达基金',
          establishDate: '2022-06-01',
          netValue: 1.856,
          totalAssets: 800000000,
          subscribers: 2100,
          rating: 4.8,
          documents: [
            { name: '产品说明书', url: '/docs/prospectus.pdf', type: 'prospectus' }
          ],
          images: ['/images/product3.jpg'],
          createdAt: '2022-05-20',
          updatedAt: '2024-01-14',
          createdBy: 'admin'
        }
      ];
      
      setProducts(mockProducts);
      setPagination(prev => ({ ...prev, total: mockProducts.length }));
    } catch (error) {
      message.error('加载产品数据失败');
    } finally {
      setLoading(false);
    }
  };

  const loadStats = async () => {
    try {
      // 模拟统计数据
      const mockStats: ProductStats = {
        total: 156,
        online: 128,
        pending: 15,
        totalAssets: 15600000000,
        avgReturn: 9.8
      };
      setStats(mockStats);
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 表格列定义
  const columns: ColumnsType<Product> = [
    {
      title: '产品信息',
      key: 'productInfo',
      width: 250,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <div style={{ fontWeight: 500, fontSize: 14 }}>{record.name}</div>
          <div style={{ fontSize: 12, color: '#666' }}>代码: {record.code}</div>
          <Space size={4}>
            <Tag color="blue">{getCategoryText(record.category)}</Tag>
            <Tag color="green">{getTypeText(record.type)}</Tag>
          </Space>
        </Space>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          draft: { color: 'default', text: '草稿' },
          pending: { color: 'orange', text: '待审核' },
          approved: { color: 'blue', text: '已审核' },
          rejected: { color: 'red', text: '已拒绝' },
          online: { color: 'green', text: '在线' },
          offline: { color: 'gray', text: '下线' }
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
      filters: [
        { text: '草稿', value: 'draft' },
        { text: '待审核', value: 'pending' },
        { text: '已审核', value: 'approved' },
        { text: '已拒绝', value: 'rejected' },
        { text: '在线', value: 'online' },
        { text: '下线', value: 'offline' }
      ]
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      width: 100,
      render: (level: number) => (
        <Space>
          <Rate disabled value={level} count={5} style={{ fontSize: 12 }} />
          <Text style={{ fontSize: 12 }}>R{level}</Text>
        </Space>
      ),
      sorter: (a, b) => a.riskLevel - b.riskLevel
    },
    {
      title: '投资门槛',
      dataIndex: 'minInvestment',
      key: 'minInvestment',
      width: 120,
      render: (amount: number) => (
        <span style={{ fontWeight: 500 }}>
          ¥{(amount / 10000).toFixed(1)}万
        </span>
      ),
      sorter: (a, b) => a.minInvestment - b.minInvestment
    },
    {
      title: '预期收益',
      dataIndex: 'expectedReturn',
      key: 'expectedReturn',
      width: 100,
      render: (rate: number, record) => (
        <Space direction="vertical" size={0}>
          <Text style={{ fontWeight: 500, color: '#52c41a' }}>
            {rate.toFixed(1)}%
          </Text>
          {record.actualReturn && (
            <Text style={{ fontSize: 11, color: '#666' }}>
              实际: {record.actualReturn.toFixed(1)}%
            </Text>
          )}
        </Space>
      ),
      sorter: (a, b) => a.expectedReturn - b.expectedReturn
    },
    {
      title: '净值/规模',
      key: 'valueAndScale',
      width: 120,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <Text style={{ fontWeight: 500 }}>{record.netValue.toFixed(3)}</Text>
          <Text style={{ fontSize: 11, color: '#666' }}>
            {(record.totalAssets / 100000000).toFixed(1)}亿
          </Text>
        </Space>
      )
    },
    {
      title: '评级',
      dataIndex: 'rating',
      key: 'rating',
      width: 100,
      render: (rating: number) => (
        <Space>
          <Rate disabled value={rating} allowHalf style={{ fontSize: 12 }} />
          <Text style={{ fontSize: 12 }}>{rating.toFixed(1)}</Text>
        </Space>
      ),
      sorter: (a, b) => a.rating - b.rating
    },
    {
      title: '管理人',
      key: 'managerInfo',
      width: 120,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <Text style={{ fontSize: 12 }}>{record.manager}</Text>
          <Text style={{ fontSize: 11, color: '#666' }}>{record.company}</Text>
        </Space>
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button 
              type="text" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewProduct(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEditProduct(record)}
            />
          </Tooltip>
          {record.status === 'pending' && (
            <>
              <Tooltip title="审核通过">
                <Button 
                  type="text" 
                  icon={<CheckCircleOutlined />} 
                  size="small"
                  style={{ color: '#52c41a' }}
                  onClick={() => handleApproveProduct(record.id)}
                />
              </Tooltip>
              <Tooltip title="审核拒绝">
                <Button 
                  type="text" 
                  icon={<CloseCircleOutlined />} 
                  size="small"
                  style={{ color: '#ff4d4f' }}
                  onClick={() => handleRejectProduct(record.id)}
                />
              </Tooltip>
            </>
          )}
          {record.status === 'approved' && (
            <Tooltip title="上线">
              <Button 
                type="text" 
                icon={<RiseOutlined />} 
                size="small"
                style={{ color: '#1890ff' }}
                onClick={() => handleOnlineProduct(record.id)}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除这个产品吗？"
            onConfirm={() => handleDeleteProduct(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                size="small"
                danger
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 获取分类文本
  const getCategoryText = (category: string) => {
    const categoryMap = {
      stock: '股票型',
      bond: '债券型',
      mixed: '混合型',
      money_market: '货币型',
      alternative: '另类投资'
    };
    return categoryMap[category as keyof typeof categoryMap] || category;
  };

  // 获取类型文本
  const getTypeText = (type: string) => {
    const typeMap = {
      fund: '基金',
      insurance: '保险',
      trust: '信托',
      wealth_management: '理财'
    };
    return typeMap[type as keyof typeof typeMap] || type;
  };

  // 处理查看产品详情
  const handleViewProduct = (product: Product) => {
    setSelectedProduct(product);
    setDetailDrawerVisible(true);
  };

  // 处理编辑产品
  const handleEditProduct = (product: Product) => {
    setEditingProduct(product);
    setModalType('edit');
    form.setFieldsValue({
      ...product,
      establishDate: dayjs(product.establishDate)
    });
    setIsModalVisible(true);
  };

  // 处理创建产品
  const handleCreateProduct = () => {
    setEditingProduct(null);
    setModalType('create');
    form.resetFields();
    setIsModalVisible(true);
  };

  // 处理审核通过
  const handleApproveProduct = async (productId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setProducts(prev => prev.map(p => 
        p.id === productId ? { ...p, status: 'approved' as const } : p
      ));
      message.success('产品审核通过');
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理审核拒绝
  const handleRejectProduct = async (productId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setProducts(prev => prev.map(p => 
        p.id === productId ? { ...p, status: 'rejected' as const } : p
      ));
      message.success('产品审核拒绝');
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理产品上线
  const handleOnlineProduct = async (productId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setProducts(prev => prev.map(p => 
        p.id === productId ? { ...p, status: 'online' as const } : p
      ));
      message.success('产品已上线');
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除产品
  const handleDeleteProduct = async (productId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setProducts(prev => prev.filter(p => p.id !== productId));
      message.success('删除产品成功');
    } catch (error) {
      message.error('删除产品失败');
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values: any) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (modalType === 'create') {
        const newProduct: Product = {
          ...values,
          id: Date.now().toString(),
          establishDate: values.establishDate.format('YYYY-MM-DD'),
          netValue: 1.000,
          totalAssets: 0,
          subscribers: 0,
          rating: 0,
          documents: [],
          images: [],
          createdAt: dayjs().format('YYYY-MM-DD'),
          updatedAt: dayjs().format('YYYY-MM-DD'),
          createdBy: 'admin'
        };
        setProducts(prev => [newProduct, ...prev]);
        message.success('创建产品成功');
      } else {
        setProducts(prev => prev.map(p => 
          p.id === editingProduct?.id 
            ? { 
                ...p, 
                ...values,
                establishDate: values.establishDate.format('YYYY-MM-DD'),
                updatedAt: dayjs().format('YYYY-MM-DD')
              } 
            : p
        ));
        message.success('更新产品成功');
      }
      
      setIsModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理批量操作
  const handleBatchOperation = (operation: string) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要操作的产品');
      return;
    }
    
    Modal.confirm({
      title: `确定要${operation}选中的${selectedRowKeys.length}个产品吗？`,
      onOk: async () => {
        try {
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          if (operation === '删除') {
            setProducts(prev => prev.filter(p => !selectedRowKeys.includes(p.id)));
          } else if (operation === '上线') {
            setProducts(prev => prev.map(p => 
              selectedRowKeys.includes(p.id) ? { ...p, status: 'online' as const } : p
            ));
          } else if (operation === '下线') {
            setProducts(prev => prev.map(p => 
              selectedRowKeys.includes(p.id) ? { ...p, status: 'offline' as const } : p
            ));
          }
          
          setSelectedRowKeys([]);
          message.success(`批量${operation}成功`);
        } catch (error) {
          message.error(`批量${operation}失败`);
        }
      }
    });
  };

  // 表格选择配置
  const rowSelection: TableProps<Product>['rowSelection'] = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE
    ]
  };

  // 文件上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    action: '/api/upload',
    onChange(info) {
      const { status } = info.file;
      if (status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    }
  };

  return (
    <div>
      {/* 页面标题和统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="产品总数"
              value={stats.total}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="在线产品"
              value={stats.online}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="管理规模"
              value={stats.totalAssets}
              precision={1}
              valueStyle={{ color: '#722ed1' }}
              formatter={(value) => `¥${(Number(value) / 100000000).toFixed(1)}亿`}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均收益"
              value={stats.avgReturn}
              precision={1}
              suffix="%"
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        {/* 搜索和筛选栏 */}
        <div style={{ marginBottom: 16 }}>
          <Row gutter={[16, 16]}>
            <Col xs={24} sm={8} md={6}>
              <Search
                placeholder="搜索产品名称、代码"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onSearch={loadProducts}
                enterButton={<SearchOutlined />}
              />
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="产品分类"
                value={categoryFilter}
                onChange={setCategoryFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="stock">股票型</Option>
                <Option value="bond">债券型</Option>
                <Option value="mixed">混合型</Option>
                <Option value="money_market">货币型</Option>
                <Option value="alternative">另类投资</Option>
              </Select>
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="状态"
                value={statusFilter}
                onChange={setStatusFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="draft">草稿</Option>
                <Option value="pending">待审核</Option>
                <Option value="approved">已审核</Option>
                <Option value="online">在线</Option>
                <Option value="offline">下线</Option>
              </Select>
            </Col>
            <Col xs={12} sm={4} md={3}>
              <Select
                placeholder="风险等级"
                value={riskFilter}
                onChange={setRiskFilter}
                style={{ width: '100%' }}
                allowClear
              >
                <Option value="1">R1 - 低风险</Option>
                <Option value="2">R2 - 中低风险</Option>
                <Option value="3">R3 - 中等风险</Option>
                <Option value="4">R4 - 中高风险</Option>
                <Option value="5">R5 - 高风险</Option>
              </Select>
            </Col>
            <Col xs={24} md={6}>
              <Space>
                <Button icon={<ReloadOutlined />} onClick={loadProducts}>
                  刷新
                </Button>
                <Button icon={<FilterOutlined />}>
                  高级筛选
                </Button>
                <Button icon={<ExportOutlined />}>
                  导出
                </Button>
              </Space>
            </Col>
          </Row>
        </div>

        {/* 操作栏 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleCreateProduct}
            >
              新增产品
            </Button>
            {selectedRowKeys.length > 0 && (
              <>
                <Button onClick={() => handleBatchOperation('上线')}>
                  批量上线
                </Button>
                <Button onClick={() => handleBatchOperation('下线')}>
                  批量下线
                </Button>
                <Button danger onClick={() => handleBatchOperation('删除')}>
                  批量删除
                </Button>
              </>
            )}
          </Space>
          <Text type="secondary">
            {selectedRowKeys.length > 0 && `已选择 ${selectedRowKeys.length} 项`}
          </Text>
        </div>

        {/* 产品表格 */}
        <Table<Product>
          columns={columns}
          dataSource={products}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
          scroll={{ x: 1400 }}
        />
      </Card>

      {/* 产品表单模态框 */}
      <Modal
        title={modalType === 'create' ? '新增产品' : '编辑产品'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFormSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="产品名称"
                rules={[{ required: true, message: '请输入产品名称' }]}
              >
                <Input placeholder="请输入产品名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="产品代码"
                rules={[{ required: true, message: '请输入产品代码' }]}
              >
                <Input placeholder="请输入产品代码" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="产品分类"
                rules={[{ required: true, message: '请选择产品分类' }]}
              >
                <Select placeholder="请选择产品分类">
                  <Option value="stock">股票型</Option>
                  <Option value="bond">债券型</Option>
                  <Option value="mixed">混合型</Option>
                  <Option value="money_market">货币型</Option>
                  <Option value="alternative">另类投资</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="type"
                label="产品类型"
                rules={[{ required: true, message: '请选择产品类型' }]}
              >
                <Select placeholder="请选择产品类型">
                  <Option value="fund">基金</Option>
                  <Option value="insurance">保险</Option>
                  <Option value="trust">信托</Option>
                  <Option value="wealth_management">理财</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="riskLevel"
                label="风险等级"
                rules={[{ required: true, message: '请选择风险等级' }]}
              >
                <Select placeholder="请选择风险等级">
                  <Option value={1}>R1 - 低风险</Option>
                  <Option value={2}>R2 - 中低风险</Option>
                  <Option value={3}>R3 - 中等风险</Option>
                  <Option value={4}>R4 - 中高风险</Option>
                  <Option value={5}>R5 - 高风险</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="minInvestment"
                label="最低投资额"
                rules={[{ required: true, message: '请输入最低投资额' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="请输入最低投资额" 
                  addonBefore="¥"
                  min={0}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="maxInvestment"
                label="最高投资额"
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="请输入最高投资额" 
                  addonBefore="¥"
                  min={0}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="expectedReturn"
                label="预期收益率"
                rules={[{ required: true, message: '请输入预期收益率' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="请输入预期收益率" 
                  addonAfter="%"
                  min={0}
                  max={100}
                  precision={2}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item
                name="managementFee"
                label="管理费率"
                rules={[{ required: true, message: '请输入管理费率' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="管理费率" 
                  addonAfter="%"
                  min={0}
                  max={10}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="custodyFee"
                label="托管费率"
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="托管费率" 
                  addonAfter="%"
                  min={0}
                  max={5}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="subscriptionFee"
                label="申购费率"
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="申购费率" 
                  addonAfter="%"
                  min={0}
                  max={5}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item
                name="redemptionFee"
                label="赎回费率"
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="赎回费率" 
                  addonAfter="%"
                  min={0}
                  max={5}
                  precision={2}
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="lockPeriod"
                label="锁定期"
                rules={[{ required: true, message: '请输入锁定期' }]}
              >
                <InputNumber 
                  style={{ width: '100%' }}
                  placeholder="请输入锁定期" 
                  addonAfter="天"
                  min={0}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="manager"
                label="基金经理"
                rules={[{ required: true, message: '请输入基金经理' }]}
              >
                <Input placeholder="请输入基金经理" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="company"
                label="管理公司"
                rules={[{ required: true, message: '请输入管理公司' }]}
              >
                <Input placeholder="请输入管理公司" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="description"
            label="产品描述"
            rules={[{ required: true, message: '请输入产品描述' }]}
          >
            <TextArea 
              rows={3} 
              placeholder="请输入产品描述" 
              maxLength={500}
              showCount
            />
          </Form.Item>
          
          <Form.Item
            name="features"
            label="产品特色"
          >
            <Select
              mode="tags"
              placeholder="请输入产品特色（支持多个）"
              style={{ width: '100%' }}
            >
              <Option value="专业管理">专业管理</Option>
              <Option value="风险分散">风险分散</Option>
              <Option value="流动性好">流动性好</Option>
              <Option value="保本保息">保本保息</Option>
              <Option value="高收益潜力">高收益潜力</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="establishDate"
            label="成立日期"
            rules={[{ required: true, message: '请选择成立日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setIsModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                {modalType === 'create' ? '创建' : '更新'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 产品详情抽屉 */}
      <Drawer
        title="产品详情"
        placement="right"
        width={700}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
      >
        {selectedProduct && (
          <Tabs 
            defaultActiveKey="basic"
            items={[
              {
                key: 'basic',
                label: '基本信息',
                children: (
                  <Descriptions column={2} bordered>
                    <Descriptions.Item label="产品名称" span={2}>{selectedProduct.name}</Descriptions.Item>
                    <Descriptions.Item label="产品代码">{selectedProduct.code}</Descriptions.Item>
                    <Descriptions.Item label="产品分类">{getCategoryText(selectedProduct.category)}</Descriptions.Item>
                    <Descriptions.Item label="产品类型">{getTypeText(selectedProduct.type)}</Descriptions.Item>
                    <Descriptions.Item label="风险等级">
                      <Rate disabled value={selectedProduct.riskLevel} count={5} style={{ fontSize: 14 }} />
                    </Descriptions.Item>
                    <Descriptions.Item label="状态">
                      <Tag color={selectedProduct.status === 'online' ? 'green' : 'orange'}>
                        {selectedProduct.status}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="投资门槛">
                      ¥{(selectedProduct.minInvestment / 10000).toFixed(1)}万
                    </Descriptions.Item>
                    <Descriptions.Item label="预期收益">{selectedProduct.expectedReturn}%</Descriptions.Item>
                    <Descriptions.Item label="实际收益">
                      {selectedProduct.actualReturn ? `${selectedProduct.actualReturn}%` : '-'}
                    </Descriptions.Item>
                    <Descriptions.Item label="净值">{selectedProduct.netValue.toFixed(3)}</Descriptions.Item>
                    <Descriptions.Item label="管理规模">
                      {(selectedProduct.totalAssets / 100000000).toFixed(1)}亿
                    </Descriptions.Item>
                    <Descriptions.Item label="基金经理">{selectedProduct.manager}</Descriptions.Item>
                    <Descriptions.Item label="管理公司">{selectedProduct.company}</Descriptions.Item>
                    <Descriptions.Item label="成立日期">{selectedProduct.establishDate}</Descriptions.Item>
                    <Descriptions.Item label="锁定期">{selectedProduct.lockPeriod}天</Descriptions.Item>
                    <Descriptions.Item label="产品评级">
                      <Rate disabled value={selectedProduct.rating} allowHalf style={{ fontSize: 14 }} />
                    </Descriptions.Item>
                    <Descriptions.Item label="产品描述" span={2}>
                      {selectedProduct.description}
                    </Descriptions.Item>
                  </Descriptions>
                )
              },
              {
                key: 'fees',
                label: '费率信息',
                children: (
                  <Descriptions column={2} bordered>
                    <Descriptions.Item label="管理费率">{selectedProduct.managementFee}%</Descriptions.Item>
                    <Descriptions.Item label="托管费率">{selectedProduct.custodyFee}%</Descriptions.Item>
                    <Descriptions.Item label="申购费率">{selectedProduct.subscriptionFee}%</Descriptions.Item>
                    <Descriptions.Item label="赎回费率">{selectedProduct.redemptionFee}%</Descriptions.Item>
                  </Descriptions>
                )
              },
              {
                key: 'documents',
                label: '产品文档',
                children: (
                  <div>
                    <div style={{ marginBottom: 16 }}>
                      <Upload {...uploadProps}>
                        <Button icon={<UploadOutlined />}>上传文档</Button>
                      </Upload>
                    </div>
                    {selectedProduct.documents.length > 0 ? (
                      <List
                        dataSource={selectedProduct.documents}
                        renderItem={(item) => (
                          <List.Item
                            actions={[
                              <Button 
                                type="link" 
                                icon={<DownloadOutlined />}
                                onClick={() => window.open(item.url)}
                              >
                                下载
                              </Button>
                            ]}
                          >
                            <List.Item.Meta
                              title={item.name}
                              description={`类型: ${item.type}`}
                            />
                          </List.Item>
                        )}
                      />
                    ) : (
                      <div style={{ textAlign: 'center', color: '#999', padding: 40 }}>
                        暂无文档
                      </div>
                    )}
                  </div>
                )
              }
            ]}
          />
        )}
      </Drawer>
    </div>
  );
};

export default ProductManagement;